package com.haust.consumer;

import com.haust.rabbit.message.dto.HaustSendEmailMessageBody;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 发送电子邮件的消费者
 * 使用的技术是，javaEmail.Spring 封装后的技术
 * Spring-boot-starter-mail
 * javaemail 发送电子邮件，需要MailSender类型的对象
 * 启动器spring-boot-start-mail自动创建，必须提供配置
 * 发送右键的邮箱是什么，服务器地址是什么，用户名和密码是什么
 */
@Component
public class SendEmailConsumer {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @RabbitListener(
            bindings = {
                    @QueueBinding(
                            value = @Queue(
                                    name = "${Haust.trade.sendMessage.queue}",
                                    autoDelete = "false"
                            ),
                            exchange = @Exchange(
                                    name = "${Haust.trade.sendMessage.exchange}",
                                    type = "${Haust.trade.sendMessage.exchangeType}"
                            ),
                            key = "${Haust.trade.sendMessage.routingKey}"
                    )
            }
    )
    public void onMessage(HaustSendEmailMessageBody messageBody) {
        //发送邮件
        //发送邮件需要什么？发送人，收件人，主题，正文
        //创建一个邮件对象
        //创建一个空的邮件对象
        MimeMessage mimeMessage =
                javaMailSender.createMimeMessage();
        //创建一个邮件对象赋值帮助工具，参数是要复制的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        try {
            helper.setFrom(from);
            helper.setTo(from);
            //helper.setCc("");  //设置抄送人
            //helper.setBcc(""); //设置密（暗）送人

            helper.setSubject("百战电商");
            StringBuilder sb = new StringBuilder();
            sb.append(messageBody.getTbUser().getUsername())
                    .append("您好")
                    .append("您本次订单为")
                    .append(messageBody.getOrderId() + "/t")
                    .append("总金额为：" + messageBody.getPayment())
                    .append("请尽快支付");
            helper.setText(sb.toString(), true);//设置正文；参数2 表示可以设置html标签

            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }

}
